package com.sdl.timesblogmp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdl.timesblogmp.exception.CustomException;
import com.sdl.timesblogmp.model.entity.Admin;
import com.sdl.timesblogmp.mapper.AdminMapper;
import com.sdl.timesblogmp.model.vo.LoginUser;
import com.sdl.timesblogmp.security.JwtService;
import com.sdl.timesblogmp.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sdl
 * @since 2020-05-11
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
    @Resource
    private AdminMapper adminMapper;
    @Resource
    private JwtService jwtService;
    @Override
    public Admin findAdminByName(String userName) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",userName);
        return adminMapper.selectOne(queryWrapper);
    }

    @Override
    public String AdminLogin(LoginUser loginUser) {
        if (StringUtils.isEmpty(loginUser.getUsername())||StringUtils.isEmpty(loginUser.getPassword())){
            throw new CustomException("用户名或密码不能为空！");
        }
        Admin admin = findAdminByName(loginUser.getUsername());
        if (admin!=null){
            if (BCrypt.checkpw(loginUser.getPassword(),admin.getPassword())){
                return jwtService.createToken(loginUser.getUsername());
            }else {
                throw new CustomException("密码错误！");
            }
        }else {
            throw new CustomException("用户不存在！");

        }
    }

    @Override
    public int updateAdmin(Admin admin) {
        int i = adminMapper.updateById(admin);
        return i;
    }

    @Override
    public int updatepwd(Integer id, String oldPwd, String newPwd) {
        Admin admin = adminMapper.selectById(id);
        if (admin==null){
            throw new CustomException("用户不存在！");
        }
        if (!BCrypt.checkpw(oldPwd,admin.getPassword())){
            throw new CustomException("原密码错误！");
        }
        admin.setPassword(BCrypt.hashpw(newPwd,BCrypt.gensalt()));
        int i = updateAdmin(admin);
        return i;
    }
}
